package bluetooth;

import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.bluetooth.RemoteDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

/**
 * @author pmp
 */

public class BtConnection
{
    private StreamConnection stream;
    private DataInputStream in;
	private DataOutputStream out;
    private BtListener  btListener;
    private String deviceAdress;

    public  BtConnection(StreamConnection _streamConnection, BtListener _btListener)
    {
        init(_streamConnection, _btListener);
    }

    public BtConnection(String _url, BtListener _btListener)
    {
        try
        {
            init((StreamConnection) Connector.open(_url), _btListener);
        } 
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }

    public String getBtAdress()
    {
        return deviceAdress;
    }

    public void sendData(String data)
    {
        try
        {
            if(out!=null)
            {
                out.writeUTF(data);
                out.flush();
            }
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
            close();
        }
    }

    public void close()
    {
        try
        {
            stream.close();
            in.close();
            out.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }

    private void init(StreamConnection _streamConnection, BtListener _btListener)
    {
         try
        {
            btListener=_btListener;
            stream = _streamConnection;
            deviceAdress=RemoteDevice.getRemoteDevice(stream).getBluetoothAddress();
            in = stream.openDataInputStream();
            out = stream.openDataOutputStream();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        Thread receiver = new Thread()
        {
            public void run()
            {
                while(true)
                {
                    try
                    {
                        btListener.dataReceived(in.readUTF(), deviceAdress);
                    }
                    catch (IOException ex)
                    {
                        btListener.connectionLost(deviceAdress);
                        close();
                        break;
                    }
                }
            }
		};
		receiver.start();
    }
}
